package com.qfedu.stussm.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.stussm.dao.CourseDao;
import com.qfedu.stussm.dto.CourseDto;
import com.qfedu.stussm.entity.Course;
import com.qfedu.stussm.entity.Score;
import com.qfedu.stussm.service.intf.CourseService;
import com.qfedu.stussm.vo.PageBeanVo;
import com.qfedu.stussm.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseDao dao;
    @Override
    public int add(Course course) {
        return dao.add(course);
    }

    @Override
    public PageBeanVo selectAll(int page, int limit,String c_name) {
        PageHelper.startPage(page, limit);
        if (c_name != null && c_name.length() >0){
            c_name = "%"+c_name+"%";
        } else {
            c_name = null;
        }

        PageInfo<CourseDto> coursePageInfo = new PageInfo<>(dao.selectAll(c_name));
        return new PageBeanVo(coursePageInfo.getTotal(), coursePageInfo.getList());
    }

    @Override
    public int update(Course course) {
        return dao.update(course);
    }

    @Override
    public int del(int c_id) {
        return dao.del(c_id);
    }
    @Override
    public R all() {
        return R.ok(dao.all());
    }

    @Override
    public void createExcel(HttpServletResponse response) throws IOException {
        //查询数据
        List<Course> list = dao.all();
        //2.设置文件下载
        //设置响应头  告知浏览器，要以附件的形式保存内容   filename=浏览器显示的下载文件名
        response.setHeader("content-disposition","attachment;filename=t_course_"+System.currentTimeMillis()+".xlsx");
        //3.生成Excel并写出
        EasyExcel.write(response.getOutputStream(),Course.class).sheet(System.currentTimeMillis()+"").doWrite(list);
    }
    @Override
    public R uploadExcel(MultipartFile file) throws IOException {
        //1.获取上传的内容 2.解析文件 3.批量新增
        //1.验证上传文件是否非空
        if(!file.isEmpty()){
            //2.获取上传内容
            InputStream is=file.getInputStream();

            //3.解析Excel
            EasyExcel.read(is,Course.class,new PageReadListener<Course>((list)->{
                //4.调用 dao 实现批量新增
                dao.addBatch(list);
            })).sheet().doRead();
        }
        return R.ok();
    }
}
